package com.sddnytsh.body_buildingsystem.screens

import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.sddnytsh.body_buildingsystem.R
import com.sddnytsh.body_buildingsystem.components.ProfileItem2
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.sddnytsh.body_buildingsystem.topic.Profile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import kotlin.Long
import kotlin.String

@Composable
fun ProfileScreen(navController: NavController) {
    var showNameDialog by remember { mutableStateOf(false) }
    var showBioDialog by remember { mutableStateOf(false) }
    var showHeightDialog by remember { mutableStateOf(false) }
    var showWeightDialog by remember { mutableStateOf(false) }
    var showBirthdayDialog by remember { mutableStateOf(false) }
    var showGenderDialog by remember { mutableStateOf(false) }
    var showRegionDialog by remember { mutableStateOf(false) }

    var userId by remember { mutableStateOf(1L) }
    var userName by remember { mutableStateOf("默认名字") }
    var userBio by remember { mutableStateOf("默认签名") }
    var userHeight: Int by remember { mutableStateOf(170) }
    var userWeight: Int by remember { mutableStateOf(60) }
    var userBirthday by remember { mutableStateOf("1990-01-01") }
    var tempGender by remember { mutableStateOf("男") }
    var tempRegion by remember { mutableStateOf("江苏 南京") }

    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current

    LaunchedEffect(Unit) {
        val profileData = fetchProfileData(userId)
        profileData?.let {
            userId = it.userId
            userName = it.username
            userBio = it.bio
            userHeight = it.height
            userWeight = it.weight
            userBirthday = it.birthday
            tempGender = it.gender
            tempRegion = it.location
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        // 顶部栏
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp)
                .background(Color.White)
                .padding(horizontal = 16.dp)
        ) {
            Icon(
                imageVector = Icons.Default.ArrowBack,
                contentDescription = "返回",
                modifier = Modifier
                    .size(24.dp)
                    .align(Alignment.CenterStart)
                    .clickable { navController.popBackStack() }
            )
            Text(
                text = "个人资料",
                style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
                modifier = Modifier.align(Alignment.Center)
            )
        }

        Divider(color = Color.LightGray, thickness = 0.5.dp)

        // 内容区域
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 16.dp)
        ) {
            Spacer(modifier = Modifier.height(24.dp))

            // 名字
            ProfileItem2(
                label = "名字",
                value = userName,
                onClick = {
                    showNameDialog = true
                }
            )

            Divider(color = Color(0xFFEEEEEE), thickness = 1.dp)

            // 性别
            ProfileItem2(
                label = "性别",
                value = tempGender, // 这里使用固定值，实际应该从 ViewModel 获取
                onClick = {
                    showGenderDialog = true
                }
            )

            Divider(color = Color(0xFFEEEEEE), thickness = 1.dp)

            // 地区
            ProfileItem2(
                label = "地区",
                value = tempRegion, // 这里使用固定值，实际应该从 ViewModel 获取
                onClick = {
                    showRegionDialog = true
                }
            )

            Divider(color = Color(0xFFEEEEEE), thickness = 1.dp)

            // 签名
            ProfileItem2(
                label = "签名",
                value = userBio,
                onClick = {
                    showBioDialog = true
                }
            )

            Divider(color = Color(0xFFEEEEEE), thickness = 1.dp)

            // 身高
            ProfileItem2(
                label = "身高",
                value = userHeight,
                onClick = {
                    showHeightDialog = true
                }
            )

            Divider(color = Color(0xFFEEEEEE), thickness = 1.dp)

            // 体重
            ProfileItem2(
                label = "体重",
                value = userWeight,
                onClick = {
                    showWeightDialog = true
                }
            )

            Divider(color = Color(0xFFEEEEEE), thickness = 1.dp)

            // 生日
            ProfileItem2(
                label = "生日",
                value = userBirthday,
                onClick = {
                    showBirthdayDialog = true
                }
            )

            Divider(color = Color(0xFFEEEEEE), thickness = 1.dp)
        }
    }

    // 修改名字对话框
    if (showNameDialog) {
        EditTextDialog(
            title = "修改名字",
            initialValue = userName,
            onConfirm = { newName ->
                userName = newName
                coroutineScope.launch {
                    updateProfile(userId, mapOf("username" to newName), context)
                }
                showNameDialog = false
            },
            onDismiss = { showNameDialog = false }
        )
    }

    // 修改签名对话框
    if (showBioDialog) {
        EditTextDialog(
            title = "修改签名",
            initialValue = userBio,
            onConfirm = { newBio ->
                userBio = newBio
                coroutineScope.launch {
                    updateProfile(userId, mapOf("bio" to newBio), context)
                }
                showBioDialog = false
            },
            onDismiss = { showBioDialog = false }
        )
    }

    // 选择性别对话框
    if (showGenderDialog) {
        SelectOptionDialog(
            title = "选择性别",
            options = listOf("男", "女"),
            selectedOption = tempGender,
            onConfirm = { selectedGender ->
                tempGender = selectedGender
                coroutineScope.launch {
                    updateProfile(userId, mapOf("gender" to selectedGender), context)
                }
                showGenderDialog = false
            },
            onDismiss = { showGenderDialog = false }
        )
    }

    // 选择地区对话框
    if (showRegionDialog) {
        EditTextDialog(
            title = "修改地区",
            initialValue = tempRegion,
            onConfirm = { newRegion ->
                tempRegion = newRegion
                coroutineScope.launch {
                    updateProfile(userId, mapOf("location" to newRegion), context)
                }
                showRegionDialog = false
            },
            onDismiss = { showRegionDialog = false }
        )
    }

    // 修改身高对话框
    if (showHeightDialog) {
        EditTextDialog(
            title = "修改身高",
            initialValue = userHeight.toString(),
            onConfirm = { newHeight ->
                val newHeightInt = newHeight.toIntOrNull()
                if (newHeightInt != null) {
                    userHeight = newHeightInt
                    coroutineScope.launch {
                        updateProfile(userId, mapOf("height" to newHeightInt), context)
                    }
                } else {
                    // Handle invalid input (e.g., show a toast or a snackbar)
                    val context = null
                    Toast.makeText(context, "请输入有效的身高值", Toast.LENGTH_SHORT).show()
                }
                showHeightDialog = false
            },
            onDismiss = { showHeightDialog = false }
        )
    }

    // 修改体重对话框
    if (showWeightDialog) {
        EditTextDialog(
            title = "修改体重",
            initialValue = userWeight.toString(),
            onConfirm = { newWeight ->
                val newWeightInt = newWeight.toIntOrNull()
                if (newWeightInt != null) {
                    userWeight = newWeightInt
                    coroutineScope.launch {
                        updateProfile(userId, mapOf("weight" to newWeightInt), context)
                    }
                } else {
                    // Handle invalid input (e.g., show a toast or a snackbar)
                    val context = null
                    Toast.makeText(context, "请输入有效的体重值", Toast.LENGTH_SHORT).show()
                }
                showWeightDialog = false
            },
            onDismiss = { showWeightDialog = false }
        )
    }

    // 修改生日对话框
    if (showBirthdayDialog) {
        EditTextDialog(
            title = "修改生日",
            initialValue = userBirthday,
            onConfirm = { newBirthday ->
                userBirthday = newBirthday
                coroutineScope.launch {
                    updateProfile(userId, mapOf("birthday" to newBirthday), context)
                }
                showBirthdayDialog = false
            },
            onDismiss = { showBirthdayDialog = false }
        )
    }
}

@Composable
fun SelectOptionDialog(
    title: String,
    options: List<String>,
    selectedOption: String,
    onConfirm: (String) -> Unit,
    onDismiss: () -> Unit
) {
    var selected by remember { mutableStateOf(selectedOption) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(title) },
        text = {
            Column {
                options.forEach { option ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { selected = option }
                            .padding(vertical = 12.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(
                            selected = selected == option,
                            onClick = { selected = option }
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(option)
                    }
                }
            }
        },
        confirmButton = {
            Button(onClick = { onConfirm(selected) }) {
                Text("确认")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

@Composable
fun EditTextDialog(
    title: String,
    initialValue: String,
    onConfirm: (String) -> Unit,
    onDismiss: () -> Unit
) {
    var textValue by remember { mutableStateOf(initialValue) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(title) },
        text = {
            OutlinedTextField(
                value = textValue,
                onValueChange = { textValue = it },
                modifier = Modifier.fillMaxWidth(),
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                keyboardActions = KeyboardActions(onDone = { onConfirm(textValue) })
            )
        },
        confirmButton = {
            Button(
                onClick = { onConfirm(textValue) },
                enabled = textValue.isNotBlank()
            ) {
                Text("确认")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

//获取数据
private suspend fun fetchProfileData(userId: Long): Profile? {
    val client = OkHttpClient()
    val request = Request.Builder()
        .url("${NetworkConfig.BASE_URL}/api/user-profile/$userId")
        .build()

    return withContext(Dispatchers.IO) {
        try {
            client.newCall(request).execute().use { response ->
                if (response.isSuccessful) {
                    val responseBody = response.body?.string()
                    if (responseBody != null) {
                        val gson = GsonBuilder().create()
                        val jsonObject = gson.fromJson(responseBody, JsonObject::class.java)

                        if (jsonObject.get("success").asBoolean) {
                            val data = jsonObject.getAsJsonObject("data")
                            Profile(
                                userId = data.get("userId")?.asLong ?: 0L,
                                username = data.get("username")?.asString ?: "",
                                bio = data.get("bio")?.asString ?: "",
                                // avatar = "",
                                gender = data.get("gender")?.asString ?: "",
                                height = data.get("height")?.asInt ?: 0,
                                weight = data.get("weight")?.asInt ?: 0,
                                birthday = data.get("birthday")?.asString ?: "",
                                location = data.get("location")?.asString ?: ""
                            )
                        } else {
                            null
                        }
                    } else {
                        null
                    }
                } else {
                    null
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}


//修改数据
private suspend fun updateProfile(userId: Long, updates: Map<String, Any>, context: Context) {
    val client = OkHttpClient()
    val gson = GsonBuilder().create()
    val json = gson.toJson(updates)

    val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull()
    val requestBody = RequestBody.create(mediaType, json)

    val request = Request.Builder()
        .url("${NetworkConfig.BASE_URL}/api/user-profile/$userId")
        .put(requestBody)
        .build()

    withContext(Dispatchers.IO) {
        try {
            client.newCall(request).execute().use { response ->
                if (!response.isSuccessful) {
                    withContext(Dispatchers.Main) {
                        Toast.makeText(context, "更新失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            withContext(Dispatchers.Main) {
                Toast.makeText(context, "网络错误: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}